#!/bin/sh
set -e

USER=iotedge
GROUP=iotedge

case "$1" in
    configure)
        if id -u $USER > /dev/null 2>&1; then
            if [ ! -d /var/lib/iotedge ]; then
                mkdir -p /var/lib/iotedge
            fi
            if [ ! -d /var/log/iotedge ]; then
                mkdir -p /var/log/iotedge
            fi
            chown ${USER}:${GROUP} /var/lib/iotedge
            chown ${USER}:${GROUP} /var/log/iotedge
            chown ${USER}:${GROUP} /etc/iotedge/config.yaml.template
            if [ ! -f /etc/iotedge/config.yaml ]; then
                cp -a /etc/iotedge/config.yaml.template /etc/iotedge/config.yaml
            fi

            chmod 755 /var/lib/iotedge
            chmod 755 /var/log/iotedge
            chmod 400 /etc/iotedge/config.yaml.template
            chmod 400 /etc/iotedge/config.yaml

        fi

        # Set the hostname
        sed -i "s/hostname: \"<ADD HOSTNAME HERE>\"/hostname: \"$(hostname)\"/g" /etc/iotedge/config.yaml

        echo "==============================================================================="
        echo ""
        echo "                              Azure IoT Edge"
        echo ""
        echo "  IMPORTANT: Please update the configuration file located at:"
        echo ""
        echo "    /etc/iotedge/config.yaml"
        echo ""
        echo "  with your device's provisioning information. You will need to restart the"
        echo "  'iotedge' service for these changes to take effect."
        echo ""
        echo "  To restart the 'iotedge' service, use:"
        echo ""
        echo "    'systemctl restart iotedge'"
        echo ""
        echo "    - OR -"
        echo ""
        echo "    /etc/init.d/iotedge restart"
        echo ""
        echo "  These commands may need to be run with sudo depending on your environment."
        echo ""
        echo "==============================================================================="
    ;;

    abort-upgrade|abort-remove|abort-deconfigure)
    ;;

    *)
        echo "postinst called with unknown argument \`$1'" >&2
        exit 1
    ;;
esac


#DEBHELPER#

exit 0
